<template>
    <div>
        <div style="display: flex; justify-content: center; align-items: center;">
            <el-form :inline="true" :model="formInline" label-width="100px">
              <el-form-item label="入库单号：">
                <el-input v-model="formInline.Number" placeholder="请输入" style="width: 150px;"></el-input>
              </el-form-item>
              <el-form-item label="入库类型：">
                <el-select v-model="formInline.Type" placeholder="请选择" style="width: 150px;">
                  <el-option
                  v-for="option in typelsit"
                  :key="option.i_TTypeId"
                  :label="option.i_TTypeName"
                  :value="option.i_TTypeId">
                </el-option> 
                  </el-select>
              </el-form-item>
              <el-form-item label="单据状态">
                <el-select v-model="formInline.Status" placeholder="请选择" style="width: 150px;">
                  <el-option label="未审核" value="未审核"></el-option>
                  <el-option label="未出库" value="未出库"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="仓库名称">
                <el-select v-model="formInline.Wmsname" placeholder="请选择" style="width: 150px;">
                  <el-option
                  v-for="option in Cklsit"
                  :key="option.w_wid"
                  :label="option.w_wname"
                  :value="option.w_wid">
                </el-option> 
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchData">查询</el-button>
              </el-form-item>
              <el-form-item>
                <el-button  @click="chongzhi">重置</el-button>
              </el-form-item>
            </el-form>
          </div >
          
          <div style="display: flex;">
            <div style="width: 90px;">
              <el-button type="primary" @click="handleAdd">新增</el-button>
            </div>
            <div style="width: 90px;">
              <el-button type="primary" @click="handleShen">审核</el-button>
            </div>
            <div style="width: 90px;">
              <el-button type="primary" @click="handleDel">删除</el-button>
            </div> 
          </div>
          <div style="overflow-x: auto;">
            <el-table :data="data" style="width: 100%" class="dataTable" @selection-change="handleSelectionChangeDel">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="i_InboundIndex" label="序号"></el-table-column>
              <el-table-column prop="i_InboundCode" label="入库单号"></el-table-column>
              <el-table-column prop="i_InboundType" label="入库类型"></el-table-column>
              <el-table-column prop="i_InboundStatus" label="单据状态">
                <template slot-scope="scope">
                  <span :style="{ color: getStatusColor(scope.row.i_InboundStatus) }">
                    {{ scope.row.i_InboundStatus }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="入库日期">
                <template slot-scope='scope'>
                  <span>{{ filterTime(scope.row.i_InboundDate) }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="i_WarehouseName" label="仓库名称"></el-table-column> -->
              <el-table-column prop="i_AssociatedCode" label="关联单号"></el-table-column>
              <el-table-column prop="i_InboundProducts" label="入库货品"></el-table-column>
              <el-table-column prop="i_Handler" label="经办人"></el-table-column>
              <el-table-column prop="i_Quantity" label="入库数量"></el-table-column>
              <el-table-column prop="i_Amount" label="入库金额"></el-table-column>
              <el-table-column prop="i_Creator" label="制单人"></el-table-column>
              <el-table-column prop="i_Department" label="所在部门"></el-table-column>
              <el-table-column label="制单时间">
                <template slot-scope='scope'>
                  <span>{{ filterTime(scope.row.i_OrderCreationTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <!-- <el-button @click="RkUpd(scope.row)" type="text">编辑</el-button> -->
                  <el-button 
                  @click="RkUpd(scope.row)" 
                  type="text"
                  :disabled="scope.row.i_InboundStatus === '未出库'" 
                >
                  编辑
                </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
              <el-pagination v-on:size-change="handleSizeChange"
              v-on:current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="rows">
  </el-pagination>

  
  <el-dialog
  title="入库新增"
  :visible.sync="rkqx"
  :size="'auto'"
>
<h3>基础信息</h3>
<el-form  ref="AddForm" :model="AddForm" :rules="rules" label-width="100px" >
  <el-row>
    <el-col :span="12">
      <el-form-item label="入库单号">
        <el-input  v-model="AddForm.rkindex" placeholder="自动获取系统编号" style="width: 200px;" disabled readonly/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="入库类型" prop="rktype">
        <el-select v-model="AddForm.rktype" placeholder="请选择" style="width: 200px;" >
          <el-option
            v-for="option in typelsit"
            :key="option.i_TTypeId"
            :label="option.i_TTypeName"
            :value="option.i_TTypeId">
          </el-option> 
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="仓库名称" prop="ckname">
        <el-select v-model="AddForm.ckname" placeholder="请选择" style="width: 200px;" >
          <el-option
            v-for="option in Cklsit"
            :key="option.w_wid"
            :label="option.w_wname"
            :value="option.w_wid">
          </el-option> 
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="入库日期" prop="rkdate">
        <el-date-picker style="width: 200px;" 
        v-model="AddForm.rkdate"
          type="date"
          format="yyyy-MM-dd"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="关联单号" prop="gldh">
        <el-input v-model="AddForm.gldh" placeholder="请输入" style="width: 200px;" >
          <template v-if="isRelatedPurchaseOrder" v-slot:append>
            <el-button @click="openModal">...</el-button>
          </template>
        </el-input>
        <el-checkbox v-model="isRelatedPurchaseOrder" label="关联进货单号" @change="clearSupplierInfo"></el-checkbox>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="供应商" prop="rkgys">
        <template v-if="!isRelatedPurchaseOrder">
          <el-select v-model="AddForm.rkgys" placeholder="请选择供应商" style="width: 200px;"  @change="getSupplierInfo">
            <el-option
              v-for="item in tableData"
              :key="item.s_MIndex"
              :label="item.s_MSupplierName"
              :value="item.s_MIndex">
            </el-option>
          </el-select>
        </template>
        <template v-else>
          <el-input v-model="AddForm.rkgys" placeholder="请输入供应商"  style="width: 200px;" readonly></el-input>
        </template>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="联系人" prop="rklxr">
        <el-input v-model="AddForm.rklxr" placeholder="请输入"  style="width: 200px;" readonly/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="联系方式" prop="rkphone">
        <el-input v-model="AddForm.rkphone" placeholder="请输入"  style="width: 200px;" readonly/>
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="经办人" prop="rkjbr">
        <el-input v-model="AddForm.rkjbr" placeholder="请输入"  style="width: 200px;" />
      </el-form-item>
      
    </el-col>
   
    <el-col :span="24">
      <el-form-item label="备注">
        <el-input v-model="AddForm.rkbz"  placeholder="请输入" />
      </el-form-item>
    </el-col>
  </el-row>
</el-form>
  <h3>入库明细</h3>
  <div style="width: 70px;">
    <!-- 添加按钮 -->
    <el-button type="primary" @click="MxAdd" style="font-size: 10px;">添加</el-button> 
  </div>
  <div style="overflow-x: auto;">
    <el-table :data="rkmxdata" style="width: 100%" class="dataTable">
      <el-table-column prop="i_IIndex" label="序号"  ></el-table-column>
      <el-table-column prop="i_IProductName" label="货品名称"></el-table-column>
      <el-table-column prop="i_IProductCode" label="货品编号"></el-table-column>
      <el-table-column prop="i_IProductType" label="货品类型"></el-table-column>
      <el-table-column prop="i_IModel" label="规格型号"></el-table-column>
      <el-table-column prop="i_IUnit" label="单位"></el-table-column>
      <el-table-column prop="i_IQuantity" label="进货数量"></el-table-column>
      <el-table-column label="入库仓位">
        <template slot-scope="scope">
          <el-select v-model="scope.row.i_IStorageLocation" placeholder="请选择">
            <el-option
              v-for="option in storageLocationOptions"
              :key="option.wl_wlid"
              :label="option.wl_wlname"
              :value="option.wl_wlid">
            </el-option> 
          </el-select>
        </template>
      </el-table-column>
      <el-table-column  label="本次入库数量">
        <template slot-scope="scope">
          <el-input v-model="scope.row.p_Shul" placeholder="请输入" @blur="checkQuantity(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="i_IUnitPrice" label="进货单价"></el-table-column>
      <el-table-column  label="金额" prop="i_IAmount">
      </el-table-column>
      <el-table-column label="生产时间">
        <template slot-scope='scope'>
          <span>{{ filterTime(scope.row.i_IProductionDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column  label="备注">
        <template slot-scope="scope">
          <el-input v-model="scope.row.i_IRemarks" placeholder="请输入"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="showDispose(scope.row)" type="text">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
    合计&nbsp;&nbsp;&nbsp;入库数量：{{ totalQuantity }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;入库总金额：{{ totalAmount }}
    </div>
  </div>
  <h3>上传附件</h3>
  <div>  
    <el-upload
    class="upload-demo"
    :action="getUploadUrl()"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-upload="beforeUpload"
    multiple
    :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过200MB</div>
  </el-upload>
  </div>  
  <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取消</el-button>
    <el-button @click="rksaveData">保存</el-button>
    
  </span>
</el-dialog>


<el-dialog
title="添加货品"
:visible.sync="tjhp"
:size="'auto'"
>
<div style="overflow-x: auto;">
  <el-table ref="tableName" :data="jhdata" style="width: 100%" class="dataTable" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="p_DSerialNumber" label="序号"></el-table-column>
    <el-table-column prop="p_DProductName" label="货品名称"></el-table-column>
    <el-table-column prop="p_DProductCode" label="货品编号"></el-table-column>
    <el-table-column prop="p_DSpecifications" label="规格型号"></el-table-column>
    <el-table-column prop="p_DProductType" label="货品类型"></el-table-column>
    <el-table-column prop="p_DUnit" label="单位"></el-table-column>
    <el-table-column prop="p_DUnitPrice" label="进货单价"></el-table-column>
    <el-table-column prop="p_DQuantity" label="进货数量"></el-table-column>
    <el-table-column prop="p_DAmount" label="进货金额"></el-table-column>
    <el-table-column prop="p_DPurchasCode" label="关联进货订单编号"></el-table-column>
  </el-table>
  <span slot="footer" class="dialog-footer">
    <el-button @click="tjhp = false">取消</el-button>
    <el-button @click="hpForm">确认</el-button>
  </span>  
</div>
</el-dialog>


 <!-- 模态框 -->
 <el-dialog :visible.sync="modalVisible" title="选择进货单">
  <!-- 模态框内容 -->
  <div style="overflow-x: auto;">
    <el-table ref="Jhname" :data="Jhname" style="width: 100%" class="dataTable" @selection-change="handleSelectionChange1"> 
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="p_OIndex" label="序号"></el-table-column>
      <el-table-column prop="p_OStatus" label="单据状态"></el-table-column>
      <el-table-column prop="p_OOrderNumber" label="货品编号"></el-table-column>
      <el-table-column prop="p_ODate" label="进货日期"></el-table-column>
      <el-table-column prop="p_OSupplier" label="供应商"></el-table-column>
      <el-table-column prop="p_ODepartment" label="进货部门"></el-table-column>
      <el-table-column prop="p_OQuantity" label="进货数量"></el-table-column>
      <el-table-column prop="p_OAmount" label="进货金额"></el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="modalVisible = false">取消</el-button>
      <el-button @click="JhgysForm">确认</el-button>
    </span>  
  </div>
  <!-- 这里放置模态框的内容 -->
</el-dialog>


<el-dialog
  title="审核"
  :visible.sync="shenhe"
  :size="'auto'"
>

<el-form ref="ShenForm" :model="ShenForm" label-width="100px" >
  <el-row>
    <el-col :span="12">
      <el-form-item label="编号" v-if="!isHidden">
        <el-input v-model="ShenForm.bh1" placeholder="请输入" style="width: 200px;" />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="审核结果">
        <el-radio-group v-model="ShenForm.jieguo">
          <el-radio label="通过">通过</el-radio>
          <el-radio label="驳回">驳回</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-col>
   
    <el-col :span="24">
      <el-form-item label="审核意见">
        <el-input v-model="ShenForm.yijian" placeholder="请输入"/>
      </el-form-item>
    </el-col>
  </el-row>
</el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="shenhe= false">取消</el-button>
      <el-button @click="ShenData">确认</el-button>
      
    </span>
</el-dialog>


        <!-- 入库管理的修改 -->
        <el-dialog
        title="入库管理修改"
        :visible.sync="Rkxiugai"
        :size="'auto'"
      >
      <el-form  ref="UpdForm" :model="UpdForm" label-width="100px" >
        <el-row>
          <el-col :span="12">
            <el-form-item label="入库单号">
              <el-input  v-model="UpdForm.rkindex1" placeholder="自动获取系统编号" style="width: 200px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库类型">
              <el-select v-model="UpdForm.rktype1" placeholder="请选择" style="width: 200px;">
                <el-option
                  v-for="option in typelsit"
                  :key="option.i_TTypeId"
                  :label="option.i_TTypeName"
                  :value="option.i_TTypeId">
                </el-option> 
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称">
              <el-select v-model="UpdForm.ckname1" placeholder="请选择" style="width: 200px;">
                <el-option
                  v-for="option in Cklsit"
                  :key="option.w_wid"
                  :label="option.w_wname"
                  :value="option.w_wid">
                </el-option> 
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库日期">
              <el-date-picker style="width: 200px;"
              v-model="UpdForm.rkdate1"
                type="date"
                format="yyyy-MM-dd"
                placeholder="请选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联单号">
              <el-input v-model="UpdForm.gldh1" placeholder="请输入" style="width: 200px;">
                <template v-if="isRelatedPurchaseOrder" v-slot:append>
                  <el-button @click="openModal1">...</el-button>
                </template>
              </el-input>
              <el-checkbox v-model="isRelatedPurchaseOrder" label="关联进货单号" @change="clearSupplierInfo1"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商">
              <template v-if="!isRelatedPurchaseOrder">
                <el-select v-model="UpdForm.rkgys1" placeholder="请选择供应商" style="width: 200px;" @change="getSupplierInfo1">
                  <el-option
                    v-for="item in tableData"
                    :key="item.s_MIndex"
                    :label="item.s_MSupplierName"
                    :value="item.S_MIndex">
                  </el-option>
                </el-select>
              </template>
              <template v-else>
                <el-input v-model="UpdForm.rkgys1" placeholder="请输入供应商" style="width: 200px;" readonly></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="UpdForm.rklxr1" placeholder="请输入" style="width: 200px;" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="UpdForm.rkphone1" placeholder="请输入" style="width: 200px;" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人">
              <el-input v-model="UpdForm.rkjbr1" placeholder="请输入" style="width: 200px;" />
            </el-form-item>
            
          </el-col>
         
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="UpdForm.rkbz1"  placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="Rkxiugai=false">取消</el-button>
        <el-button @click="rksaveData1">保存</el-button>
        
      </span>
      </el-dialog>
    </div>
</template>

<script>
import $http from '../router/base.js';
  import axios from 'axios';
  import { MessageBox } from 'element-ui';
export default {
    data(){
        return{
          Rkxiugai:false,//入库管理的修改模态框
          isHidden: true, // 控制文本框显示与隐藏的变量
          shenhe:false,//审核的模态框
          ShenForm:{//审核
          bh1:'',
          jieguo:'',
          yijian:''
        },
          Jhname:[],
          isRelatedPurchaseOrder: false, // 默认不关联进货单号
          modalVisible: false, // 控制模态框显示与隐藏的变量
          tjhp:false,
          jhdata:[],
          rkqx:false,//入库管理添加
          rkmxdata:[],//入库明细表的数据
            data:[],
            storageLocationOptions:[],//库位的下拉框
            Cklsit:[],//仓库的下拉框
            typelsit:[],//类型的下拉框
            tableData:[],
        currentPage: 1,
        pageSize: 10,
        rows: 0, // 数据总条数
        fileList:[],
            formInline: {
            Number: '',
            Type:'',
            Status: '',
            Wmsname:'',
        },
        AddForm:{
            rkindex:'',
            rktype:'',
            ckname:'',
            rkdate:'',
            gldh:'',
            rkgys:'',
            rklxr:'',
            rkphone:'',
            rkjbr:'',
            rkbz:''
        },
        UpdForm:{
            rkindex1:'',
            rktype1:'',
            ckname1:'',
            rkdate1:'',
            gldh1:'',
            rkgys1:'',
            rklxr1:'',
            rkphone1:'',
            rkjbr1:'',
            rkbz1:''
        },
        rules: {
          rkphone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^[0-9]{11}$/, message: '联系方式必须为11位数字', trigger: 'blur' }
  ],
  rkdate: [
    { required: true, message: '请输入日期', trigger: 'blur' },
  ],
  rkgys: [
    { required: true, message: '请选择供应商', trigger: 'blur' },
  ],
  rklxr: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
  ],
  ckname: [
    { required: true, message: '请选择仓库', trigger: 'blur' },
  ],
  rktype: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],

},
         orderNumber:'',
         selectedRows: [], // 选中的行数据
        }
    },methods: {
      getStatusColor(status) {
      const statusColorMap = {
       
        '未出库': 'orange',
        '未审核': 'red',
        
      };
      return statusColorMap[status];
    },
      generateCode() {
      // 生成随机大写字母
      const randomLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));

      // 生成当前日期
      const currentDate = new Date().toISOString().slice(0, 10).replace(/-/g, '');

      // 生成4个随机数字
      const randomDigits = Math.floor(1000 + Math.random() * 9000);

      // 组合成编号
      return randomLetter + currentDate + randomDigits;
    },
      //修改的数据保存到数据库
      rksaveData1(){
        $http.put("api/InboundS/Upd1", {
          i_InboundIndex:this.UpdForm.rkindex1,
          i_InboundType:  this.UpdForm.rktype1,
          i_WarehouseName:  this.UpdForm.ckname1,
          i_InboundDate: this.UpdForm.rkdate1,
          i_AssociatedCode: this.UpdForm.gldh1,
          i_OSupplier:this.UpdForm.rkgys1,
          i_OContactPerson:this.UpdForm.rklxr1,
          i_OContactInformation:this.UpdForm.rkphone1,
          i_Handler:this.UpdForm.rkjbr1,
          i_Reamr:this.UpdForm.rkbz1,
  }).then(res => {
    if (res) {
      this.$message({
        message: '修改成功！',
        type: 'success'
      });

      this.Rkxiugai = false;
      this.searchData(); // 重新填充销售机会列表
    }
  })
  .catch(err => {
    this.$message({
      message: '修改失败！',
      type: 'error'
    });
  });
      },
      clearSupplierInfo1() {
        this.UpdForm.gldh1='';
  this.UpdForm.rkgys1 = ''; // 清空供应商
  this.UpdForm.rklxr1 = ''; // 清空联系人
  this.UpdForm.rkphone1 = ''; // 清空联系方式
},
      //根据供应商查询联系人和联系方式
      getSupplierInfo1() {
        $http.get('api/Suppliermanagement/QuName/QuName', {
      params: {
        Name:this.UpdForm.rkgys1
      }
    }).then((response) => {
      this.UpdForm.rklxr1 = response.s_MContactPerson;
          this.UpdForm.rkphone1 = response.s_MContactNumber;
         
    }).catch((error) => {
      console.log(error);
    });
    },
      openModal1() {
      // 关联单号点击按钮时打开模态框
      this.modalVisible = true;
      this.Jgs();
    },
      //入库修改
      RkUpd(row){
        this.Rkxiugai=true;
        this.Wqu();
            this.Ckqu();
            this.Typequ();
            this.Gys();
         this.UpdForm.rkindex1=row.i_InboundIndex;
         this.UpdForm.rktype1=row.i_InboundType;
         this.UpdForm.ckname1=row.i_WarehouseName;
         this.UpdForm.rkdate1=row.i_InboundDate;
         this.UpdForm.gldh1=row.i_AssociatedCode;
         this.UpdForm.rkgys1=row.i_OSupplier;
         this.UpdForm.rklxr1=row.i_OContactPerson;
         this.UpdForm.rkphone1=row.i_OContactInformation;
         this.UpdForm.rkjbr1=row.i_Handler;
         this.UpdForm.rkbz1=row.i_Reamr;
      },
        //入库审核
        ShenData(){
        $http.put(`api/InboundS/RkShen?to=${this.ShenForm.jieguo}`, {
          i_InboundIndex: this.ShenForm.bh1,
          p_Reviewcomments: this.ShenForm.yijian,
         
  }).then(res => {
    if (res) {
      this.$message({
        message: '审核成功！',
        type: 'success'
      });

      this.shenhe = false;
      this.searchData(); // 重新填充销售机会列表
    }
  })
  .catch(err => {
    this.$message({
      message: '审核失败！',
      type: 'error'
    });
  });
 
      },
      handleShen(){
          this.shenhe=true;
          this.ShenForm.bh1=this.selectedPOIndex;
         
      },
      // 处理复选框选中事件
      handleSelectionChangeDel(selection) {
  this.selectedIds = selection.map(item => item.i_InboundIndex);
  if (selection && selection.length > 0) {
        const selectedRow = selection[0]; // 获取选中的第一行数据
        this.selectedPOIndex = selectedRow.i_InboundIndex; // 获取选中行的编号
      } else {
        this.selectedPOIndex = ''; // 如果没有选中行，则清空选中行的编号
      }
      this.selectedRows = selection;//无法删除已审核的数据
       console.log("1"+this.selectedIds);
       console.log("2"+this.selectedPOIndex);
},//批量删除
    handleDel() {
      const hasUnstoredData = this.selectedRows.some(row => row.i_InboundStatus === '未出库');
  if (!hasUnstoredData) {
    MessageBox.confirm('存在未入库的数据，确定删除所选单据？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 执行删除操作的逻辑
      $http.delete('api/InboundS/RkDel', {
        data: this.selectedIds
      })
      .then(response => {
        this.$message({
          message: '删除成功！',
          type: 'success'
        });
        this.Qu();
        this.searchData();
      })
      .catch(error => {
        this.$message({
          message: '删除失败！',
          type: 'error'
        });
      });
    }).catch(() => {
      // 用户点击取消按钮时执行的操作，这里不需要执行任何操作
    });
  } else {
    this.$message.warning('无法删除已审核的数据');
  }
    },
      checkQuantity(row) {
    // 获取进货数量
    const quantity = row.i_IQuantity;
    // 获取本次入库数量
    const inputQuantity = row.p_Shul;

    // 如果本次入库数量大于进货数量，则提示错误并将输入框置空
    if (inputQuantity > quantity) {
      this.$message.error('本次入库数量不能大于进货数量');
      row.p_Shul = '';
    }
  },
      handleSelectionChange1(selection) {
    // 将选中行保存到数据中
    this.selectedRows = selection;
  },
      Jgs(){
        $http.get('api/InboundS/Jhqu',{              
            }).then((response)=>{
               this.Jhname=response;
              
            }).catch((error)=>{
               console.log(error);
              
            })
      },
      JhgysForm()//关联单号选择进货单号确认
      {
    if (this.selectedRows.length === 0) {
      this.$message.error('请选择进货单');
      return;
    }

    // 假设只选择了一行数据
    const selectedRow = this.selectedRows[0];

    // 判断是否关联进货单号
    if (this.isRelatedPurchaseOrder) {
      this.AddForm.gldh = selectedRow.p_OOrderNumber; // 关联单号
      this.AddForm.rkgys = selectedRow.p_OSupplier; // 供应商
      this.AddForm.rklxr = selectedRow.p_OContactPerson; // 联系人
      this.AddForm.rkphone = selectedRow.p_OContactInformation; // 联系方式

      this.UpdForm.gldh1 = selectedRow.p_OOrderNumber; // 关联单号
      this.UpdForm.rkgys1 = selectedRow.p_OSupplier; // 供应商
      this.UpdForm.rklxr1 = selectedRow.p_OContactPerson; // 联系人
      this.UpdForm.rkphone1 = selectedRow.p_OContactInformation; // 联系方式
    } 

    // 关闭模态框
    this.modalVisible = false;
  }
      ,
      clearSupplierInfo() {
        this.AddForm.gldh='';
  this.AddForm.rkgys = ''; // 清空供应商
  this.AddForm.rklxr = ''; // 清空联系人
  this.AddForm.rkphone = ''; // 清空联系方式
},
      //根据供应商查询联系人和联系方式
      getSupplierInfo() {
        $http.get('api/Suppliermanagement/QuName/QuName', {
      params: {
        Name:this.AddForm.rkgys
      }
    }).then((response) => {
      this.AddForm.rklxr = response.s_MContactPerson;
          this.AddForm.rkphone = response.s_MContactNumber;
         
    }).catch((error) => {
      console.log(error);
    });
    },
      openModal() {
      // 关联单号点击按钮时打开模态框
      this.modalVisible = true;
      this.Jgs();
    },
       //查询供应商表作为下拉框
       Gys(){
        $http.get('api/Suppliermanagement/Qu',{              
            }).then((response)=>{
               this.tableData=response;
              
            }).catch((error)=>{
               console.log(error);
              
            })
      },
       //入库类型的下拉框
       Typequ(){
        $http.get('api/Inventorytype/Iqu',{              
            }).then((response)=>{
               this.typelsit=response;
              
            }).catch((error)=>{
               console.log(error);
              
            })
       },
       //仓库名称的下拉框
       Ckqu(){
        $http.get('api/Warehouse/Wqu',{              
            }).then((response)=>{
               this.Cklsit=response;
              
            }).catch((error)=>{
               console.log(error);
              
            })
       },
       //库位的下拉框
       Wqu(){
        $http.get('api/Warehouselocation/Wqu',{              
            }).then((response)=>{
               this.storageLocationOptions=response;
              
            }).catch((error)=>{
               console.log(error);
              
            })
       },
      beforeUpload(file) {
      const isImage = file.type.includes('image');
      if (!isImage) {
        this.$message.error('只能上传图片文件');
      }
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!isLt200M) {
        this.$message.error('上传文件大小不能超过200MB');
      }
      return isImage && isLt200M;
    },
     // 获取动态的上传URL
     getUploadUrl() {
      // 构建上传URL，并将this.AddForm.jindex的值添加到URL中
      return `http://localhost:5084/api/PublicAttachment/Upload?num=${this.generateCode()}`;
    },
    handlePreview(file) {
  const reader = new FileReader();
  reader.onload = (e) => {
    const imageUrl = e.target.result;
    // 在这里可以使用 imageUrl 来显示预览图片
    // 例如，将 imageUrl 设置为 img 标签的 src 属性
    // 或者在模态框中显示预览图片
    console.log('预览图片:', imageUrl);
  };
  reader.readAsDataURL(file.raw);
},
handleRemove(file) {
  const index = this.fileList.indexOf(file);
  if (index !== -1) {
    this.fileList.splice(index, 1);
    // 在这里可以向服务器发送请求，删除对应的文件
    console.log('删除文件:', file.name);
  }
},
        //入库表分页模糊查询
        searchData(){
          const { Number, Type, Status, Wmsname } = this.formInline;
          $http.get('api/InboundS/Fye', {
      params: {
        pageSize: this.pageSize,
        currentPage: this.currentPage,
        Number: Number,
        Type:Type,
        Status: Status,
        WName:Wmsname
      }
    }).then((response) => {
      this.data = response;
      console.log(this.data);
      this.handleTotalRecords();
    }).catch((error) => {
      console.log(error);
    });
        },
        Qu(){//总行数
        $http.get('api/InboundS/Qu', {
    }).then((response) => {
      this.rows = response.length;
     
    }).catch((error) => {
      console.log(error);
    });
       },
        //清空文本框
        chongzhi(){
           this.formInline.Number='';
           this.formInline.Type='';
           this.formInline.Status='';
           this.formInline.Wmsname='';
        },
       
      //入库明细添加
      MxAdd(){
        this.tjhp=true;
           this.HoupQu();
      },
      //入库明细添加货品确认
      hpForm() {
        const selectedRows = this.$refs.tableName.selection; // 获取所有选中的行数据
   // 获取当前日期时间
const currentDate = new Date();

// 将时分秒设为 0
currentDate.setHours(0, 0, 0, 0);

// 格式化日期为 'YYYY-MM-DD' 格式
const formattedDate = currentDate.toISOString().slice(0, 10);
      // 检查是否至少选择了一行
      if (selectedRows.length > 0) {
        // 遍历选中的每一行数据
        selectedRows.forEach(row => {
          // 将选中行数据添加到显示数据数组中
          this.rkmxdata.push({
            i_IIndex: this.rkmxdata.length + 1, // 序号为当前数组长度加1
            i_IProductName: row.p_DProductName,
            i_IProductCode: row.p_DProductCode,
            i_IProductType: row.p_DProductType,
            i_IModel: row.p_DSpecifications,
            i_IUnit: row.p_DUnit,
            i_IQuantity: row.p_DQuantity,
            i_IUnitPrice:row.p_DUnitPrice,
            i_IAmount:row.p_DAmount,
            i_IProductionDate:formattedDate
          });
        });
        
        // 关闭弹窗
        this.tjhp = false;
      } else {
        // 提示用户至少选择一行数据
        this.$message.warning('请至少选择一行数据！');
      }
  
},
      //入库明细删除
      showDispose(row){
        if (confirm("确定删除吗")) {
      $http.delete(`api/Inventorydetails/Del?id=${row.i_IIndex}`)
      .then(response => {
        this.$message({
                  message: '删除成功！',
                  type: 'success'
                });
                this.RkQU();
      })
      .catch(error => {
        this.$message({
                  message: '删除失败！',
                  type: 'success'
                });
      });
  }
      },
       //进货明细查询的全部
       HoupQu(){
            $http.get(`api/Purchasedetails/Qu?dh=${this.AddForm.gldh}`,{              
            }).then((response)=>{
               this.jhdata=response;
            }).catch((error)=>{
               console.log(error);
               
            })
      },
        // 处理复选框选中状态改变事件
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
        handleAdd(){//入库管理添加
            this.rkqx=true;
            //this.RkQU();
            this.Wqu();
            this.Ckqu();
            this.Typequ();
            this.Gys();
        }
        ,filterTime(date) {
  if (date) {
    return date.split('T')[0];
  } else {
    return '';
  }
},
      // 处理页码变化
      handleSizeChange: function (size) {
    this.pageSize = size;
    this.searchData();
    },
      handleCurrentChange: function (page) {
    this.currentPage = page;
    this.searchData();
},

handleTotalRecords(){
        if (this.totalRecords === 1) {  
        this.totalPages = 2; 
      } else {  
        this.totalPages = (this.pageSize * this.currentPage) + (this.totalRecords % this.pageSize === 0 ? 0 : this.totalRecords % this.pageSize) - 1;  
      }  },
rksaveData(){
  //把数据保存到入库管理表
  this.$refs.AddForm.validate((valid) => {
    if (valid) {
      // 保存操作
      this.saveForm();
  this.savea();
  this.sfrk();
  this.rkqx=false;
    } else {
      // 表单验证失败，可以在这里进行相应的提示或处理
    }
  });
 
 
},

sfrk(){//回写进货订单表是否入库
  // 检查是否包含换行符
const hasNewline = this.AddForm.gldh.includes('\r') || this.AddForm.gldh.includes('\n');

// 如果包含换行符，则去除
const associatedCode = hasNewline ? this.AddForm.gldh.replace(/[\r\n]+/g, '') : this.AddForm.gldh;
const totalQuantity = this.rkmxdata.reduce((total, item) => total + (parseFloat(item.p_Shul) || 0), 0);

  const data = {
    p_OOrderNumber: associatedCode, 
    p_OStatus: totalQuantity === 0 ? '未入库' : (totalQuantity === this.rkmxdata.reduce((total, item) => total + item.i_IQuantity, 0) ? '已入库' : '部分入库'),
  };
  $http.put("api/InboundS/Upd", data)
    .then(res => {
      // 处理后端的响应
      if (res) {
        this.$message({
          message: '添加成功！',
          type: 'success'
        });
      }
    })
    .catch(err => {
      // 处理请求失败
      this.$message({
        message: '添加失败！',
        type: 'error'
      });
    });
},
//入库明细表的添加
savea(){ 
    // 遍历数的每一行数据
    this.rkmxdata.forEach(row => {
      const cw=row.i_IStorageLocation.toString();
      const postData = {
        i_IProductName: row.i_IProductName,
        i_IProductCode: row.i_IProductCode,
        i_IProductType: row.i_IProductType,
        i_IModel: row.i_IModel,
        i_IUnit:row.i_IUnit,
        i_IStorageLocation:cw,
        i_IUnitPrice: row.i_IUnitPrice,
        i_IQuantity: row.p_Shul,
        i_IAmount:row.i_IAmount,
        i_IRemarks:row.i_IRemarks,
        i_InboundCode:this.orderNumber
      };
      // 发送每一行数据到服务器进行添加
      $http.post("api/Inventorydetails/Add", postData)
        .then(res => {
          if (res) {
            this.$message({
              message: '添加成功！',
              type: 'success'
            });
          } else {
            this.$message({
              message: '添加失败！',
              type: 'error'
            });
          }            
        })
        .catch(error => {
          console.error('添加失败:', error);
          this.$message.error('添加失败，请稍后重试！');
        });
    });
},
saveForm() {//把数据保存到入库管理表
 
 // 获取当前日期
 const currentDate = new Date();
// 将日期格式化为 'yyyy-MM-dd' 形式
const formattedDate = currentDate.toISOString().slice(0, 10); // 获取 'yyyy-MM-dd' 部分
const gys=this.AddForm.rkgys.toString();
const type=this.AddForm.rktype.toString();
const ck=this.AddForm.ckname.toString();
// 检查是否包含换行符
const hasNewline = this.AddForm.gldh.includes('\r') || this.AddForm.gldh.includes('\n');
 // 生成编号
 this.orderNumber = this.generateCode();
// 如果包含换行符，则去除
const associatedCode = hasNewline ? this.AddForm.gldh.replace(/[\r\n]+/g, '') : this.AddForm.gldh;
$http.post("api/InboundS/Add", {
    i_InboundCode: this.orderNumber,
    i_InboundType: type,
    i_InboundStatus: '未审核',
    i_OSupplier:gys,
    i_OContactPerson:this.AddForm.rklxr,
    i_OContactInformation:this.AddForm.rkphone,
    i_InboundDate: this.AddForm.rkdate,
    i_WarehouseName: ck,
    i_AssociatedCode: associatedCode,
    i_InboundProducts:this.concatenatedProductNames,//货品名称
    i_Handler:this.AddForm.rkjbr,
    i_Quantity: this.totalQuantity,
    i_Amount: this.totalAmount,
    i_Creator: 'admin',
    i_Department: '进货部',
    i_OrderCreationTime: formattedDate, // 使用正确的日期变量
    i_ApprovalTime: null, 
    i_Approver: null, 
    i_Reamr: this.AddForm.rkbz,
    p_Reviewcomments:null
  })
  .then(res => {
    if (res) { 
      this.$message({
        message: '添加成功！',
        type: 'success'
      });
      this.searchData();
  this.Qu();
    } else {
      this.$message({
        message: '添加失败！',
        type: 'error' // 应该是 error 类型
      });
    }
  })
  .catch(error => {
    console.error('请求失败:', error);
    this.$message.error('请求失败，请稍后重试！');
  });
},
cancel(){
  this.rkmxdata = []; // 清空显示数据数组
      this.rkqx = false; // 关闭弹窗
},
    },mounted(){
      this.searchData();
      this.Qu();
      this.Ckqu();
            this.Typequ();
    },
    computed: {
    totalQuantity() {
      // 计算入库数量的总和
      return this.rkmxdata.reduce((total, item) => total + (parseFloat(item.p_Shul) || 0), 0);
     
    },
    concatenatedProductNames() {
      return this.rkmxdata
        .map(item => `${item.i_IProductName}`) // 将每个货品名称转换为所需格式
        .join('，'); // 使用逗号拼接所有转换后的货品名称
    },
    totalAmount() {
      // 计算金额的总和
      return this.rkmxdata.reduce((total, item) => total + ((item.p_Shul || 0) * (item.i_IUnitPrice || 0)), 0);
    },
  },
}
</script>

<style scoped>

</style>